package com.apimanage.gateway.config;

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import io.netty.channel.ChannelOption;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.handler.timeout.WriteTimeoutHandler;
import reactor.netty.http.client.HttpClient;
import reactor.netty.http.HttpProtocol;
import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * WebClient配置类
 * 增强配置以解决HTTP版本不兼容问题
 */
@Configuration
public class WebClientConfig {


    // 添加一个不带负载均衡的WebClient，专门用于内部服务调用
    @Bean("directWebClient")
    public WebClient directWebClient() {
        HttpClient httpClient = HttpClient.create()
                .protocol(HttpProtocol.HTTP11)
                .compress(true)
                .keepAlive(true)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 30000)
                .responseTimeout(Duration.ofSeconds(30))
                .doOnConnected(conn -> conn
                        .addHandlerLast(new ReadTimeoutHandler(30, TimeUnit.SECONDS))
                        .addHandlerLast(new WriteTimeoutHandler(30, TimeUnit.SECONDS))
                )
                // 添加全局错误处理
                .doOnResponseError((response, throwable) -> {
                    System.err.println("WebClient请求错误: " + throwable.getMessage() + ", 响应状态码: " + response.status().code());
                });

        return WebClient.builder()
                .clientConnector(new ReactorClientHttpConnector(httpClient))
                .defaultHeader("Content-Type", "application/json")
                .defaultHeader("Accept", "application/json")
                .defaultHeader("User-Agent", "APIGateway/1.0")
                .codecs(configurer -> {
                    configurer.defaultCodecs().maxInMemorySize(16 * 1024 * 1024);
                })
                // 添加请求拦截器便于调试
                .filter((request, next) -> {
                    System.out.println("WebClient请求: " + request.method() + " " + request.url());
                    return next.exchange(request);
                })
                .build();
    }
    
    /**
     * 创建一个带负载均衡的WebClient（备用方案）
     * 注意：此方法主要作为示例，当前需求是避免负载均衡直接调用
     */
    @Bean("loadBalancedWebClient")
    @LoadBalanced
    public WebClient.Builder loadBalancedWebClientBuilder() {
        return WebClient.builder()
                .defaultHeader("Content-Type", "application/json")
                .defaultHeader("Accept", "application/json");
    }
}